/**
 * 
 */
package com.wubo.sec.core;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.wubo.common.util.StringUtils;

/**
 * 记住用户登录成功的登录页面<br/>
 * <b>只用于当系统有多个登录页面的情况</b>
 * @author WuBo
 * @CreateDate 2012-2-15
 */
public class UserAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws ServletException, IOException {
		 String loginPage = request.getHeader("Referer");
		 if(StringUtils.hasText(loginPage)){
			 String contextPath = getContextPath(request);
			 
			 if(loginPage.indexOf(contextPath) != -1 && loginPage.indexOf("login") != -1){
				 String loginPageURI = getRequestURI(loginPage, contextPath);
				 
				 UserLoginPageHelper.setLoginPageCookie(loginPageURI, request, response);
			 }
		 }
		 
		 super.onAuthenticationSuccess(request, response, authentication);
	}
	
	private String getContextPath(HttpServletRequest request){
		String contextPath = request.getContextPath();
		 if(contextPath.indexOf("http://") == -1 && contextPath.indexOf("https://") == -1){
			 int port = request.getServerPort();
			 if(! contextPath.startsWith("/")){
				 contextPath = "/"+contextPath;
			 }
			 contextPath = request.getServerName()+(port==80?"":":"+port)+contextPath;
		 }
		 return contextPath;
	}
	
	protected String getRequestURI(String url, String contextPath){
		int idx = url.indexOf(contextPath);
		int paramIdx = url.indexOf("?");
		
		if(paramIdx != -1){
			url =  url.substring(idx+contextPath.length(), paramIdx);
		}else{
			url = url.substring(idx+contextPath.length());
		}
		int semiIdx = url.indexOf(";");
		if(semiIdx != -1){
			return url.substring(0, semiIdx);
		}
		return url;
	}
	
}
